package com.beiji.usercentert.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.beiji.usercentert.comoon.ErrorCode;
import com.beiji.usercentert.constant.UserConstant;
import com.beiji.usercentert.exception.BusinessException;
import com.beiji.usercentert.mapper.UserMapper;
import com.beiji.usercentert.model.domain.User;
import com.beiji.usercentert.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.beiji.usercentert.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author wangzhi
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-06-23 17:17:47
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    //加盐
    private static final String SALT = "beiji";


    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {

        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        //不包含特殊字符
        String vaildPattern = "^[a-zA-Z0-9_]{4,}$";
        Matcher matcher = Pattern.compile(vaildPattern).matcher(userAccount);
        boolean matches = matcher.matches();
        if (!matches) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR, "有特殊字符");
        }
        if (userAccount.length() < 4) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR, "用户长度");
        }
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR, "用户密码");
        }
        if (!userPassword.equals(checkPassword)) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
        }
        //查看星球编号是否合法
        if (planetCode.length() > 5 ) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号不合法");
        }
        //检验用户是否存在
        User user = this.lambdaQuery()
                .eq(User::getUserAccount, userAccount)
                .one();
        if (ObjectUtils.isNotEmpty(user)) {
            throw  new BusinessException(ErrorCode.NULL_DATA, "数据重复");
        }

        //星球编号是否重复
        User user1 = this.lambdaQuery()
                .eq(User::getPlanetCode, planetCode)
                .one();
        if (ObjectUtils.isNotEmpty(user1)) {
            throw  new BusinessException(ErrorCode.NULL_DATA, "数据重复");
        }

        //密码加密
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        //插入用户数据
        User addUser = new User();
        addUser.setUserAccount(userAccount);
        addUser.setUserPassword(encryptPassword);
        addUser.setPlanetCode(planetCode);
        boolean result = this.save(addUser);
        if (!result) {
            return -1;
        }
        return addUser.getId();
    }


    @Override
    public User doLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //校验
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //不包含特殊字符
        String vaildPattern = "^[a-zA-Z0-9_]{4,}$";
        Matcher matcher = Pattern.compile(vaildPattern).matcher(userAccount);
        boolean matches = matcher.matches();
        if (!matches) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userAccount.length() < 4) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userPassword.length() < 8) {
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //md5加密
        String safetyPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
        //根据账号和密码查询用户是否存在
        User user = this.lambdaQuery()
                .eq(User::getUserAccount, userAccount)
                .eq(User::getUserPassword, safetyPassword)
                .one();

        if (ObjectUtils.isEmpty(user)) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User safetyUser = getSafetyUser(user);

        //记录用户登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, safetyUser);

        //返回脱敏后的用户信息
        return safetyUser;
    }

    //脱敏
    public  User getSafetyUser(User originUser) {
        //脱敏
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        return safetyUser;
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @Override
    public Integer userLogout(HttpServletRequest request) {
        //移除session
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return 1;
    }
}




